package net.lcqf.tcp.send.message;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import net.lcqf.tcp.game.MatchRoom;
import net.lcqf.tcp.game.room.RoomManager;
import net.lcqf.tcp.request.RoomRequest;
import net.lcqf.tcp.response.room.RoomResponse;
import net.lcqf.tcp.send.MessageBaseService;
import net.lcqf.tcp.send.MessageFactory;
import net.lcqf.tcp.send.RequestType;
import net.lcqf.tcp.utils.LocalCacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/3/5 16:28
 * // +----------------------------------------------------------------------
 */

@Service
public class Room implements MessageBaseService {

    @Override
    @PostConstruct
    public void init() {
        MessageFactory.register(RequestType.CONFIRM_ROOM, this);
        MessageFactory.register(RequestType.CANCEL_ROOM, this);
    }

    @Override
    public Object sendMessage(Channel channel, String msg) {
        RoomRequest request = JSONUtil.toBean(msg, RoomRequest.class);

        checkPlayerBehavior(request, channel);

        return null;
    }


    /**
     * 检测玩家行为
     * @param request 请求参数
     * @param channel 消息通道
     */
    private void checkPlayerBehavior(RoomRequest request, Channel channel) {
        RoomManager roomClass = LocalCacheUtil.ACTIVE_ROOM.get(request.getRoomId());

        switch (request.getType()) {
            case 4:
                boolean ready = roomClass.confirmReady(channel.id().asShortText());
                if (ready) {
                    RoomResponse room = new RoomResponse();
                    room.setRoomId(request.getRoomId());
                    room.setChannelId(channel.id().asShortText());
                    room.setReady(true);

                    MatchRoom.broadcastToPlayer(RequestType.UPDATE_ROOM.ordinal(), JSONUtil.toJsonStr(room), roomClass.matchPlayerList);
                }
                break;
            case 6:
                System.out.println("走了取消房间的操作");
                // TODO 后续可对非正常下线玩家进行惩罚（已经确认、已经开始游戏）
                boolean cancel = roomClass.cancelReady(channel.id().asShortText());
                LocalCacheUtil.ACTIVE_ROOM.remove(request.getRoomId());
                break;
            default:
                // 其他行为，直接断开连接
                if (channel.isActive()) { channel.close(); }
        }
    }
}
